from datetime import date
import re
from flask import Blueprint,request,jsonify
import json
from db import db1
from werkzeug.utils import redirect
bp_login=Blueprint('sflogin',__name__)


# 可写可不写
@bp_login.route('/login',methods=['POST'])
def login():
    if request.method==['POST']:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select nikename,password from user where nikename='%s' and password='%s'"%(data['nikename'],data['password'])
        res = db1.find(sql)
        if res:
            return jsonify({'code':200})
        else:
            return jsonify({'code':20010,'mes':'用户或密码错误'})

# 获取uid，token
@bp_login.route('/code')
def sf_login():
    token='sfseefese'
    uid=788
    return jsonify({'code':200,'token':token,'uid':uid})

# 授权登录按钮
@bp_login.route('/find',methods=['POST'])
def find():
   
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select * from sf_login inner join users on sf_login.user_id=users.id where token='%s' and uid='%s'"%(data['token'],data['uid'])
        res = db1.find(sql)
        if res:
            url='http://localhost:8888/queren?type=1'+'&mobile='+res['mobile']+'&uid='+str(res['uid'])+'&token='+res['token']
            return jsonify({'code':200,'url':url})
        else:
            url='http://localhost:8888/queren?type=2'+'&uid='+str(data['uid'])+'&token='+data['token']
            return jsonify({'code':200,'url':url})
 
#  绑定手机号按钮
@bp_login.route('/mobile',methods=['POST'])
def mobile():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "select * from users where mobile='%s'"%data['mobile']
    res = db1.find(sql)
    if res:
        return jsonify({'code':30010,'mes':'手机已经绑定过'})
    else:
        sqlq = "insert into users(mobile) values('%s')"%(data['mobile'])
        db1.update(sqlq)
        sql2 = "select id from users where mobile='%s'"%(data['mobile'])
        res2 = db1.find(sql2)
        sql3 = "insert into sf_login(user_id,platfrom,uid,token) values(%d,'微博','%s','%s')"%(int(res2['id']),data['uid'],data['token'])
        db1.update(sql3)
        return jsonify({'code':200}) 